<!--
 * @Author: t-xiangqun.li t-xiangqun.li@pcitc.com
 * @Date: 2025-10-20 17:04:45
 * @LastEditors: lixiangqun
 * @LastEditTime: 2025-11-13 16:42:54
 * @FilePath: \electrconVue\src\views\Home.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="w-[80%] mx-auto h-full">
    <div class="h-[85%] flex items-center">
      <ProviderSelect :items="providerList" v-model="currentProvider" />
    </div>
    <div class="h-[15%] flex items-center">
      <MessageInput :disabled="!currentProvider" @create="onCreate" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import ProviderSelect from "../components/ProviderSelect.vue";
import MessageInput from "../components/MessageInput.vue";
import { ConversationProps, ProviderProps } from "../types";
import { computed, onMounted, ref } from "vue";
import { db } from "../db";
import { useRouter } from "vue-router";
import { useConversationStore } from "../stores/conversation";
import { useMessageStore } from "../stores/message";
const router = useRouter();
const providerList = ref<ProviderProps[]>([]);
const currentProvider = ref<string>("");
const modelInfo = computed(() => {
  const [providerId, selectedModel] = currentProvider.value.split("/");
  return {
    providerId,
    selectedModel,
  };
});
const conversationStore = useConversationStore();

onMounted(async () => {
  providerList.value = await db.providers.toArray();
});
let copiedImagePath: string | null;
const onCreate = async (value: string, imagePath?: string) => {
  const { providerId, selectedModel } = modelInfo.value;
  const date = new Date().toISOString();
  console.log(imagePath, "图片路径");
  if (imagePath) {
    try {
      copiedImagePath = await window.electronAPI.copyImageToUserDir(imagePath);
      console.log(copiedImagePath, "复制后地址"); //C:\Users\15478\AppData\Roaming\electron-ai\images\icon.png 复制后地址
    } catch (error) {
      throw new Error("复制错误", error);
    }
  }
  const conversationData: Omit<ConversationProps, "id"> = {
    title: value,
    selectedModel,
    createdAt: date,
    updatedAt: date,
    providerId: parseInt(providerId),
  };
  const conversationId: number =
    await conversationStore.createConversation(conversationData);

  const messageId = await db.messages.add({
    content: value,
    type: "question",
    conversationId,
    createdAt: date,
    updatedAt: date,
    ...(copiedImagePath && { imagePath: copiedImagePath }), // 如果图片存在
  });
  router.push({
    path: "/conversation",
    query: { id: conversationId, init: messageId },
  });
};
</script>
